package com.haibara.codesubmiteval.judge.strategy;

import com.haibara.codesubmiteval.properties.DangerousCodeProperties;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
public class DangerousCodeDetector {

    @Resource
    private DangerousCodeProperties dangerousCodeProperties;
    private List<Pattern> DANGER_PATTERNS;

    @PostConstruct
    public void init() {
        List<String> dangerousCode = dangerousCodeProperties.getPatterns();
        DANGER_PATTERNS = dangerousCode.stream().map(s -> Pattern.compile(
                s,
                Pattern.CASE_INSENSITIVE
        )).toList();
    }

    /**
     * 检测脚本中是否包含高危命令
     *
     * @param code 待检测的脚本内容
     * @return 检测到的危险命令列表（空列表表示安全）
     */
    public List<String> detectDangerousCodes(String code) {
        List<String> threats = new ArrayList<>();
        String[] lines = code.split("\\r?\\n");

        for (String line : lines) {
            // 移除注释和前后空白
            String cleanLine = line.replaceAll("#.*", "").trim();
            if (cleanLine.isEmpty()) continue;

            // 逐行匹配高危模式
            for (Pattern pattern : DANGER_PATTERNS) {
                Matcher matcher = pattern.matcher(cleanLine);
                if (matcher.find()) {
                    threats.add(line.trim());
                    break; // 避免同一行多次匹配
                }
            }
        }
        return threats;
    }
}